<template>
  <div class="sales-return-order-add-container">
    <div class="page-header">
      <h2>新增销售退货</h2>
      <div class="header-actions">
        <el-button @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
    </div>

    <!-- 基础信息 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="base-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="退货单号">
              <el-input v-model="formData.salesOrderItemCode" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售单号" prop="shopOrderCode">
              <div class="field-with-button">
                <el-input v-model="formData.shopOrderCode" placeholder="请选择" readonly />
                <el-button link type="primary" @click="openSalesOrderDialog">...</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期" prop="returnDate">
              <el-date-picker
                v-model="formData.returnDate"
                type="date"
                placeholder="请选择"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="销售日期">
              <el-input v-model="formData.salesDate" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input v-model="formData.customerName" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model="formData.contact" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input v-model="formData.contactPhone" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售部门">
              <el-input v-model="formData.deptName" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售负责人">
              <el-input v-model="formData.auditor" placeholder="自动带出" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="退货原因">
              <el-input v-model="formData.returnReason" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 退货明细 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>退货明细</span>
          <div class="card-actions">
            <el-button type="success" @click="openGoodsDialog" :disabled="!formData.shopOrderCode">
              <el-icon><Plus /></el-icon>
              添加
            </el-button>
            <el-button @click="removeSelectedDetails" :disabled="!detailSelection.length">
              <el-icon><Delete /></el-icon>
              移除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="formData.details"
        border
        style="width: 100%"
        height="420px"
        @selection-change="handleDetailSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="goodsName" label="货品名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="goodsCode" label="货品编号" width="140" show-overflow-tooltip />
        <el-table-column prop="specificationModel" label="规格型号" width="140" show-overflow-tooltip />
        <el-table-column prop="unitName" label="单位" width="80" align="center" />
        <el-table-column label="销售数量" width="110" align="right">
          <template #default="{ row }">{{ formatNumber(row.salesQuantity) }}</template>
        </el-table-column>
        <el-table-column label="已出库" width="100" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.alreadyStockOutQuantity ?? row.stockOutQuantity) }}
          </template>
        </el-table-column>
        <el-table-column label="未出库" width="100" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.unStockOutQuantity ?? row.unstockOutQuantity) }}
          </template>
        </el-table-column>
        <el-table-column label="本次退货数量" width="140" align="right">
          <template #default="{ row }">
            <el-input
              v-model="row.returnQuantity"
              type="number"
              size="small"
              min="0"
              @input="() => handleReturnQuantityChange(row)"
              @blur="() => handleReturnQuantityChange(row, true)"
            />
          </template>
        </el-table-column>
        <el-table-column label="销售单价" width="110" align="right">
          <template #default="{ row }">
            {{ toCurrency(row.salesUnitPrice ?? row.salesPrice) }}
          </template>
        </el-table-column>
        <el-table-column label="退货金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ toCurrency(row.returnAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="160">
          <template #default="{ row }">
            <el-input v-model="row.remark" size="small" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ $index }">
            <el-button type="danger" link size="small" @click="removeDetail($index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="detail-summary">
        <span>记录数：{{ detailCount }} 项</span>
        <span>退货数量：{{ formatNumber(totalReturnQuantity) }}</span>
        <span>退货金额：¥{{ toCurrency(totalReturnAmount) }}</span>
      </div>
    </el-card>

    <div class="form-actions">
      <el-button type="success" :loading="saveLoading" @click="handleSave">
        <el-icon><Check /></el-icon>
        保存
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
      <el-button @click="handleBack">
        <el-icon><Close /></el-icon>
        取消
      </el-button>
    </div>

    <!-- 销售单选择 -->
    <el-dialog v-model="salesOrderDialogVisible" title="选择销售单" width="80%" :close-on-click-modal="false">
      <div class="dialog-section">
        <el-form :inline="true" :model="salesOrderSearch" class="dialog-search">
          <el-form-item label="销售单号">
            <el-input v-model="salesOrderSearch.shopOrderCode" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="salesOrderSearch.customerName" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="销售部门">
            <el-input v-model="salesOrderSearch.deptName" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="salesOrderLoading" @click="searchSalesOrders">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetSalesOrderSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="salesOrderList"
          border
          height="400px"
          highlight-current-row
          :loading="salesOrderLoading"
          @row-click="handleSalesOrderRowClick"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="shopOrderCode" label="销售单号" width="160" show-overflow-tooltip />
          <el-table-column prop="shopOrderDate" label="销售日期" width="140" show-overflow-tooltip />
          <el-table-column prop="customerName" label="客户名称" width="140" show-overflow-tooltip />
          <el-table-column prop="contact" label="联系人" width="120" show-overflow-tooltip />
          <el-table-column prop="contactPhone" label="联系方式" width="140" show-overflow-tooltip />
          <el-table-column prop="deptName" label="销售部门" width="140" show-overflow-tooltip />
          <el-table-column prop="auditor" label="销售负责人" width="140" show-overflow-tooltip />
          <el-table-column prop="shopQuantity" label="销售数量" width="120" align="right">
            <template #default="{ row }">{{ formatNumber(row.shopQuantity) }}</template>
          </el-table-column>
          <el-table-column prop="shopAmount" label="销售金额" width="140" align="right">
            <template #default="{ row }">¥{{ toCurrency(row.shopAmount) }}</template>
          </el-table-column>
        </el-table>

        <div class="dialog-pagination">
          <el-pagination
            v-model:current-page="salesOrderPagination.pageIndex"
            v-model:page-size="salesOrderPagination.pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="salesOrderPagination.total"
            @size-change="loadSalesOrders"
            @current-change="loadSalesOrders"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="salesOrderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSalesOrder">确定</el-button>
      </template>
    </el-dialog>

    <!-- 货品选择 -->
    <el-dialog v-model="goodsDialogVisible" title="添加货品" width="80%" :close-on-click-modal="false">
      <!-- 销售单信息摘要 -->
      <div class="goods-dialog-header">
        <span class="info-item">
          <label>销售单号：</label>
          <span>{{ formData.shopOrderCode }}</span>
        </span>
        <span class="info-item">
          <label>销售日期：</label>
          <span>{{ formData.salesDate }}</span>
        </span>
        <span class="info-item">
          <label>客户名称：</label>
          <span>{{ formData.customerName }}</span>
        </span>
        <span class="info-item">
          <label>金额：</label>
          <span>{{ selectedSalesOrderInfo.shopAmount }}</span>
        </span>
        <span class="info-item">
          <label>数量：</label>
          <span>{{ selectedSalesOrderInfo.shopQuantity }}</span>
        </span>
      </div>

      <el-table
        :data="goodsList"
        border
        height="440px"
        :loading="goodsLoading"
        @selection-change="handleGoodsSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="goodsCode" label="货品编号" width="140" show-overflow-tooltip />
        <el-table-column prop="goodsName" label="货品名称" width="160" show-overflow-tooltip />
        <el-table-column prop="specificationModel" label="规格型号" width="140" show-overflow-tooltip />
        <el-table-column prop="unitName" label="单位" width="80" align="center" />
        <el-table-column label="销售数量" width="110" align="right">
          <template #default="{ row }">{{ formatNumber(row.salesQuantity) }}</template>
        </el-table-column>
        <el-table-column label="已出库" width="100" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.alreadyStockOutQuantity ?? row.stockOutQuantity) }}
          </template>
        </el-table-column>
        <el-table-column label="未出库" width="100" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.unStockOutQuantity ?? row.unstockOutQuantity) }}
          </template>
        </el-table-column>
        <el-table-column label="销售单价" width="120" align="right">
          <template #default="{ row }">¥{{ toCurrency(row.salesUnitPrice ?? row.salesPrice) }}</template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="goodsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGoodsSelection">添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, getCurrentInstance, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Check, Close, Delete, Plus, Refresh, Search } from '@element-plus/icons-vue'

const router = useRouter()
const { proxy } = getCurrentInstance()

const formRef = ref(null)
const saveLoading = ref(false)
const detailSelection = ref([])

const formData = reactive({
  //随机数
  salesOrderItemCode: 'EF' + Date.now().toString(),
  returnDate: '',
  salesDate: '',
  shopOrderCode: '',
  customerName: '',
  contact: '',
  contactPhone: '',
  deptName: '',
  auditor: '',
  returnReason: '',
  remark: '',
  details: []
})

const formRules = {
  shopOrderCode: [{ required: true, message: '请选择销售单号', trigger: 'change' }],
  returnDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }]
}

const totalReturnQuantity = computed(() => formData.details.reduce((sum, item) => sum + toNumber(item.returnQuantity), 0))
const totalReturnAmount = computed(() => formData.details.reduce((sum, item) => sum + toNumber(item.returnAmount), 0))
const detailCount = computed(() => formData.details.length)

const salesOrderDialogVisible = ref(false)
const salesOrderList = ref([])
const salesOrderLoading = ref(false)
const salesOrderPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})
const salesOrderSearch = reactive({
  shopOrderCode: '',
  customerName: '',
  deptName: ''
})
const selectedSalesOrder = ref(null)
const selectedSalesOrderInfo = ref({
  shopAmount: 0,
  shopQuantity: 0
})

const goodsDialogVisible = ref(false)
const goodsList = ref([])
const goodsLoading = ref(false)
const selectedGoods = ref([])

const toNumber = (value) => {
  const num = Number(value)
  return Number.isNaN(num) ? 0 : num
}

const toCurrency = (value) => {
  return toNumber(value).toFixed(2)
}

const formatNumber = (value) => {
  const num = toNumber(value)
  return Number.isInteger(num) ? num : num.toFixed(2)
}

const formatDateString = (input) => {
  if (!input) return ''
  const date = new Date(input)
  if (!Number.isNaN(date.getTime())) {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
  }
  if (typeof input === 'string' && input.length >= 10) {
    return input.substring(0, 10)
  }
  return ''
}

const getDefaultDate = () => {
  const date = new Date()
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

const resetFormData = () => {
  formData.salesOrderItemCode = 'EF' + Date.now().toString(),
  formData.returnDate = getDefaultDate()
  formData.salesDate = ''
  formData.shopOrderCode = ''
  formData.customerName = ''
  formData.contact = ''
  formData.contactPhone = ''
  formData.deptName = ''
  formData.auditor = ''
  formData.returnReason = ''
  formData.remark = ''
  formData.details = []
  detailSelection.value = []
}

const openSalesOrderDialog = () => {
  salesOrderDialogVisible.value = true
  loadSalesOrders()
}

const loadSalesOrders = async () => {
  salesOrderLoading.value = true
  try {
    const params = {
      pageIndex: salesOrderPagination.pageIndex,
      pageSize: salesOrderPagination.pageSize,
      ...salesOrderSearch
    }

    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    console.log('=== 开始获取销售单列表 ===')
    console.log('请求参数:', params)

    const response = await proxy?.http?.get('/api/ShopOrder/pageWithRelations', params, false)

    console.log('销售单列表接口响应:', response)

    if (isSuccessResponse(response)) {
      const { list, total } = extractListAndTotal(response)
      console.log('提取的原始列表:', list)
      
      salesOrderList.value = list.map(normalizeSalesOrder)
      salesOrderPagination.total = total ?? list.length
      
      console.log('格式化后的销售单列表:', salesOrderList.value)
    } else {
      console.error('销售单接口响应失败:', response)
      salesOrderList.value = []
      salesOrderPagination.total = 0
    }
  } catch (error) {
    console.error('获取销售单列表失败:', error)
    ElMessage.error('获取销售单列表失败，请稍后重试')
    salesOrderList.value = []
    salesOrderPagination.total = 0
  } finally {
    salesOrderLoading.value = false
  }
}

const isSuccessResponse = (resp) => {
  if (!resp) return false
  if (resp.success === true) return true
  if (resp.status === true || resp.status === 1 || resp.status === 0) return true
  if (resp.code === 0 || resp.code === 200) return true
  return false
}

const extractListAndTotal = (resp) => {
  let list = []
  let total = resp.total ?? resp.count ?? resp.records ?? 0

  // 优先检查最常见的数据结构
  if (Array.isArray(resp.data)) {
    // 直接在 data 字段的数组
    list = resp.data
    total = resp.total ?? resp.count ?? list.length
  } else if (Array.isArray(resp.rows)) {
    // 直接在 rows 字段
    list = resp.rows
    total = resp.total ?? resp.records ?? list.length
  } else if (Array.isArray(resp.data?.rows)) {
    // data.rows 嵌套结构
    list = resp.data.rows
    total = resp.data.total ?? resp.data.records ?? list.length
  } else if (Array.isArray(resp.data?.data)) {
    // data.data 嵌套结构
    list = resp.data.data
    total = resp.data.total ?? resp.data.count ?? list.length
  } else if (Array.isArray(resp.list)) {
    // list 字段
    list = resp.list
    total = resp.total ?? resp.count ?? list.length
  } else if (resp.data && typeof resp.data === 'object' && !Array.isArray(resp.data)) {
    // data 是对象但不是数组，可能需要进一步解析
    if (Array.isArray(resp.data.list)) {
      list = resp.data.list
      total = resp.data.total ?? resp.data.count ?? list.length
    }
  }

  return { list, total }
}

const normalizeSalesOrder = (item = {}) => {
  // 优先从 data 对象中提取字段，这是新接口的数据结构
  const data = item.data ?? item
  
  // 格式化日期，去掉时间部分
  const rawDate = data.shopOrderDate ?? item.shopOrderDate ?? item.ShopOrderDate ?? ''
  const formattedDate = formatDateString(rawDate)
  
  return {
    raw: item,
    id: data.id ?? item.id ?? item.Id ?? item.shopOrderId,
    shopOrderCode: data.shopOrderCode ?? item.shopOrderCode ?? item.ShopOrderCode ?? '',
    shopOrderDate: formattedDate, // 直接使用格式化后的日期
    salesDate: formattedDate,
    customerName: data.customerName ?? item.customerName ?? item.CustomerName ?? item.supplierName ?? '',
    contact: data.contact ?? item.contact ?? data.contacter ?? item.contacter ?? item.Contact ?? '',
    contactPhone: data.contactPhone ?? item.contactPhone ?? item.ContactPhone ?? item.mobile ?? '',
    deptName: data.deptName ?? item.deptName ?? item.DeptName ?? '',
    auditor: data.auditor ?? item.auditor ?? item.salesPrincipal ?? item.salesPerson ?? item.userName ?? '',
    remark: data.remark ?? item.remark ?? item.Remark ?? '',
    // 使用 shopAllNum 作为销售数量
    shopQuantity: toNumber(data.shopAllNum ?? item.shopAllNum ?? data.shopQuantity ?? item.shopQuantity ?? 0),
    // 使用 shopAllMoney 作为销售金额
    shopAmount: toNumber(data.shopAllMoney ?? item.shopAllMoney ?? data.shopAmount ?? item.shopAmount ?? 0)
  }
}

const handleSalesOrderRowClick = (row) => {
  selectedSalesOrder.value = row
}

const confirmSalesOrder = () => {
  if (!selectedSalesOrder.value) {
    ElMessage.warning('请选择销售单')
    return
  }

  const order = selectedSalesOrder.value
  formData.shopOrderCode = order.shopOrderCode
  formData.customerName = order.customerName
  formData.contact = order.contact
  formData.contactPhone = order.contactPhone
  formData.deptName = order.deptName
  formData.auditor = order.auditor
  formData.salesDate = order.salesDate ?? formatDateString(order.shopOrderDate)

  // 保存销售单的金额和数量信息，用于货品对话框显示
  selectedSalesOrderInfo.value = {
    shopAmount: order.shopAmount || 0,
    shopQuantity: order.shopQuantity || 0
  }

  salesOrderDialogVisible.value = false
  selectedSalesOrder.value = null

  // 切换销售单后清除已有明细
  formData.details = []
  detailSelection.value = []

  ElMessage.success('销售单信息已填充，请继续选择退货明细')
}

const searchSalesOrders = () => {
  salesOrderPagination.pageIndex = 1
  loadSalesOrders()
}

const resetSalesOrderSearch = () => {
  salesOrderSearch.shopOrderCode = ''
  salesOrderSearch.customerName = ''
  salesOrderSearch.deptName = ''
  salesOrderPagination.pageIndex = 1
  loadSalesOrders()
}

const openGoodsDialog = async () => {
  if (!formData.shopOrderCode) {
    ElMessage.warning('请先选择销售单号')
    return
  }
  goodsDialogVisible.value = true
  await loadGoodsList()
}

const loadGoodsList = async () => {
  goodsLoading.value = true
  try {
    console.log('=== 开始获取销售明细 ===')
    console.log('销售单号:', formData.shopOrderCode)
    
    // 使用正确的接口路径：GetSalesOrderDetailsByCode (Details是复数)
    const response = await proxy?.http?.get(
      `/api/SalesReturnOrderModel/GetSalesOrderDetailsByCode?shopOrderCode=${formData.shopOrderCode}`,
      null,
      false
    )

    console.log('销售明细接口响应:', response)

    if (isSuccessResponse(response)) {
      const { list } = extractListAndTotal(response)
      console.log('提取的列表数据:', list)
      
      if (!list || list.length === 0) {
        ElMessage.warning('该销售单暂无明细数据')
        goodsList.value = []
      } else {
        goodsList.value = list.map(normalizeGoodsRow)
        console.log('格式化后的货品列表:', goodsList.value)
      }
    } else {
      console.error('接口响应失败:', response)
      const errMsg = response?.msg || response?.message || '获取销售明细失败'
      ElMessage.error(errMsg)
      goodsList.value = []
    }
  } catch (error) {
    console.error('获取销售明细异常:', error)
    ElMessage.error('获取销售明细失败：' + (error.message || '请检查网络连接'))
    goodsList.value = []
  } finally {
    goodsLoading.value = false
  }
}

const normalizeGoodsRow = (item = {}) => {
  console.log('正在格式化货品行:', item)
  
  // 根据后端接口实际返回字段适配
  const salesQty = toNumber(item.salesQuantity ?? 0)
  const shippedQty = toNumber(item.stockOutQuantity ?? 0)
  const unShippedQty = toNumber(item.unstockOutQuantity ?? 0)
  const unitPrice = toNumber(item.salesPrice ?? 0)

  const result = {
    raw: item,
    // 接口实际返回字段映射
    rowNumber: item.rowNumber ?? 0,
    shopOrderDetailId: item.shopOrderDetailId ?? item.id,
    goodsId: item.goodsId,
    goodsCode: item.goodsCode ?? '',
    goodsName: item.goodsName ?? '',
    goodsType: item.goodsType ?? '',
    specificationModel: item.specModel ?? '',
    unitId: item.unitId,
    unitName: item.unitName ?? '',
    // 数量相关字段
    salesQuantity: salesQty,
    stockOutQuantity: shippedQty,
    alreadyStockOutQuantity: shippedQty,
    unstockOutQuantity: unShippedQty,
    unStockOutQuantity: unShippedQty,
    // 价格相关字段
    salesPrice: unitPrice,
    salesUnitPrice: unitPrice,
    salesAmount: toNumber(item.salesAmount ?? 0),
    // 退货相关字段
    returnQuantity: 0,
    returnAmount: 0,
    remark: '',
    stockOutDetailId: item.stockOutDetailId ?? null
  }
  
  console.log('格式化结果:', result)
  return result
}

const handleGoodsSelectionChange = (selection) => {
  selectedGoods.value = selection
}

const confirmGoodsSelection = () => {
  if (!selectedGoods.value.length) {
    ElMessage.warning('请选择需要退货的货品')
    return
  }

  selectedGoods.value.forEach((item) => {
    const exists = formData.details.find((detail) => detail.shopOrderDetailId === item.shopOrderDetailId)
    if (!exists) {
      formData.details.push({ ...item })
    }
  })

  goodsDialogVisible.value = false
  selectedGoods.value = []

  if (!formData.details.length) {
    ElMessage.warning('未添加任何退货明细')
  } else {
    ElMessage.success('已添加退货明细，请填写退货数量')
  }
}

const handleDetailSelectionChange = (selection) => {
  detailSelection.value = selection
}

const removeDetail = (index) => {
  formData.details.splice(index, 1)
}

const removeSelectedDetails = () => {
  if (!detailSelection.value.length) {
    return
  }
  const ids = new Set(detailSelection.value.map((item) => item.shopOrderDetailId))
  formData.details = formData.details.filter((item) => !ids.has(item.shopOrderDetailId))
  detailSelection.value = []
}

const handleReturnQuantityChange = (row, showTip = false) => {
  if (!row) return
  let qty = toNumber(row.returnQuantity)
  if (qty < 0) qty = 0
  if (row.unStockOutQuantity !== undefined && qty > toNumber(row.unStockOutQuantity)) {
    qty = toNumber(row.unStockOutQuantity)
    if (showTip) {
      ElMessage.warning('本次退货数量不能大于未出库数量')
    }
  }
  row.returnQuantity = qty
  row.returnAmount = toNumber(qty) * toNumber(row.salesUnitPrice)
}

const validateDetails = () => {
  if (!formData.details.length) {
    ElMessage.warning('请添加退货明细')
    return false
  }

  const invalidItem = formData.details.find((item) => toNumber(item.returnQuantity) <= 0)
  if (invalidItem) {
    ElMessage.warning('请填写所有退货明细的本次退货数量')
    return false
  }

  return true
}

const buildPayload = () => {
  const mainData = {
    salesOrderItemCode: formData.salesOrderItemCode || '0',
    returnDate: formData.returnDate,
    shopOrderCode: formData.shopOrderCode,
    salesDate: formData.salesDate,
    customerName: formData.customerName,
    contact: formData.contact,
    contactPhone: formData.contactPhone,
    deptName: formData.deptName,
    auditor: formData.auditor,
    returnReason: formData.returnReason,
    remark: formData.remark,
    totalQuantity: totalReturnQuantity.value,
    totalAmount: Number(totalReturnAmount.value.toFixed(2))
  }

  const detailData = formData.details.map((item, index) => ({
    rowNumber: item.rowNumber ?? index + 1,
    shopOrderDetailId: item.shopOrderDetailId,
    goodsId: item.goodsId,
    goodsCode: item.goodsCode,
    goodsName: item.goodsName,
    goodsType: item.goodsType,
    specModel: item.specificationModel,
    specificationModel: item.specificationModel,
    unitId: item.unitId,
    unitName: item.unitName,
    salesQuantity: toNumber(item.salesQuantity),
    stockOutQuantity: toNumber(item.alreadyStockOutQuantity),
    alreadyStockOutQuantity: toNumber(item.alreadyStockOutQuantity),
    unstockOutQuantity: toNumber(item.unStockOutQuantity),
    unStockOutQuantity: toNumber(item.unStockOutQuantity),
    returnQuantity: toNumber(item.returnQuantity),
    salesPrice: toNumber(item.salesUnitPrice),
    salesUnitPrice: toNumber(item.salesUnitPrice),
    salesAmount: toNumber(item.salesAmount),
    returnAmount: Number(toNumber(item.returnAmount).toFixed(2)),
    stockOutDetailId: item.stockOutDetailId,
    remark: item.remark || ''
  }))

  return { mainData, detailData }
}

const handleSave = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) {
      return
    }

    if (!validateDetails()) {
      return
    }

    const payload = buildPayload()
    
    console.log('=== 提交销售退货单数据 ===')
    console.log('主表数据:', payload.mainData)
    console.log('明细数据:', payload.detailData)

    try {
      saveLoading.value = true
      const response = await proxy?.http?.post(
        '/api/SalesReturnOrderModel/SaveSalesReturnOrder',
        payload,
        false
      )

      if (isSuccessResponse(response)) {
        ElMessage.success('销售退货单保存成功')
        handleBack(true)  // 保存成功后直接返回，不弹确认框
      } else {
        const message = response?.msg || response?.message || '保存失败，请稍后重试'
        ElMessage.error(message)
      }
    } catch (error) {
      console.error('保存销售退货单失败:', error)
      ElMessage.error('保存失败，请稍后重试')
    } finally {
      saveLoading.value = false
    }
  })
}

const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有内容吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      resetFormData()
      formRef.value?.clearValidate()
      ElMessage.success('表单已重置')
    })
    .catch(() => {})
}

const handleBack = (skipConfirm = false) => {
  // 如果 skipConfirm 为 true（保存成功后），直接返回不弹确认框
  if (skipConfirm) {
    router.push('/wms.salesreturnorder/salesreturnorder')
    return
  }
  
  // 正常取消时，如果有未保存内容则弹出确认框
  if (formData.details.length || formData.shopOrderCode || formData.returnReason || formData.remark) {
    ElMessageBox.confirm('退出前未保存的内容将丢失，确认返回吗？', '提示', {
      confirmButtonText: '返回',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        router.push('/wms.salesreturnorder/salesreturnorder')
      })
      .catch(() => {})
  } else {
    router.push('/wms.salesreturnorder/salesreturnorder')
  }
}

onMounted(() => {
  resetFormData()
})
</script>

<style scoped>
.sales-return-order-add-container {
  padding: 20px;
  min-height: 100vh;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.card-actions {
  display: flex;
  gap: 12px;
}

.field-with-button {
  display: flex;
  align-items: center;
  gap: 8px;
}

.field-with-button :deep(.el-input) {
  flex: 1;
}

.detail-summary {
  margin-top: 16px;
  display: flex;
  gap: 24px;
  font-weight: 500;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.dialog-search {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 16px;
}

.dialog-pagination {
  display: flex;
  justify-content: center;
  margin-top: 12px;
}

.goods-dialog-header {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
}

.goods-dialog-header .info-item {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.goods-dialog-header .info-item label {
  font-weight: 600;
  margin-right: 4px;
  color: #909399;
}

.goods-dialog-header .info-item span {
  color: #303133;
}

@media (max-width: 1200px) {
  .field-with-button {
    flex-direction: column;
    align-items: stretch;
  }

  .field-with-button el-button {
    width: 100%;
  }
}
</style>

